<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="getTitle" :width="drawerWidth" @ok="handleSubmit">
    <BasicForm @register="registerForm"></BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref} from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { editUserFormSchema } from '../data/data';
import {Api, getUserInfo, userUpdate } from '../data/api';
import { useAppInject } from '@apps/antd-admin/src/hooks/web/use-app-inject';

const { getIsMobile } = useAppInject();
const drawerWidth = ref('550px');
if (unref(getIsMobile)) {
  drawerWidth.value = '80%';
}
// 声明Emits
const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);

const [registerForm, { resetFields, setFieldsValue, saveOrUpdate,formSubmit }] = useForm({
  rowKey: 'userId',
  labelWidth: 150,
  labelCol: { span: 4 },
  saveApi: Api.save,
  updateApi: Api.update,
  schemas: editUserFormSchema,
  showActionButtonGroup: false,
});

const getTitle = computed(() => (!isUpdate.value ? '新增用户' : '编辑用户'));
const [registerDrawer, { changeLoading,setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields();
  changeLoading(false);
  isUpdate.value = !!data?.isUpdate;
  let record = data.record;
  let userId = record.userId;
  if (userId) {
    let userId = record.userId;
    let queryData = await getUserInfo({ userId: userId });
    if (queryData) {
      queryData.accountName=queryData.mobile
      await setFieldsValue({
        ...queryData,
      });
      return;
    }
  }
  let newData = { userId: record.userId };
  await setFieldsValue({
    ...newData,
  });
});

async function handleSubmit() {
  await formSubmit({
    emit: emit,
    setDrawerProps,
    closeDrawer
  });
}
</script>
